<template>
    <div class="uploader-box">
        <!-- 图像展示 -->
        <template v-if="fileList.length > 0">
            <!-- 单图模式 -->
            <div class="avatar-box" v-if="fileList.length <= 1">
                <img :src="fileList[0].url" class="avatar" />
                <i class="el-icon-close" @click="removeUpload(0)"></i>
            </div>

            <!-- 多图模式 -->
            <div class="uploader-list" v-else>
                <div
                    class="avatar-box"
                    v-for="(item, index) in fileList"
                    :key="item.file"
                >
                    <img :src="item.url" class="avatar" />
                    <i class="el-icon-close" @click="removeUpload(index)"></i>
                </div>
            </div>
        </template>

        <!-- 上传组件 -->
        <template v-else>
            <el-upload
                class="avatar-uploader"
                action=""
                :limit="limit"
                :show-file-list="false"
                :before-upload="beforeUpload"
            >
                <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </template>
    </div>
</template>

<script>
import * as qiniu from "qiniu-js";

export default {
    name: "Uploader",
    props: {
        /**
         * 对应V-model
         */
        value: {
            type: String,
            default: "",
        },
        /**
         * 允许最大上传个数
         */
        limit: {
            type: Number,
            default: 10,
        },
        /**
         * 上传类型
         */
        fileType: {
            type: Array,
            default: () => ["images"],
        },
        /**
         * 多图上传
         */
        multiple: {
            type: Boolean,
            default: false,
        },
        /**
         * 上传成功回调
         */
        onSuccess: {
            type: Function,
            default: () => {},
        },
        /**
         * 删除操作回调
         */
        onRemove: {
            type: Function,
            default: () => {},
        },
    },
    data() {
        return {
            fileList: [], // 上传成功列表
        };
    },
    methods: {
        /**
         * 初始化组件数据
         */
        init(file) {
            if (!this.multiple) {
                // 单图上传
                const fileObj = {
                    name: file,
                    url: this.$utils.splicingImageUrl(file),
                };

                this.fileList = [fileObj];
            } else {
                // 多图上传
                let fileArr = file.split(",");
                let fileList = [];

                fileList = fileArr.map((item) => ({
                    name: item,
                    url: this.$utils.splicingImageUrl(item),
                }));

                this.fileList = fileList;
            }
        },
        /**
         * 数据重置
         */
        reset() {
            this.fileList = [];
        },

        /**
         * 组件上传处理
         */
        beforeUpload(file) {
            let that = this;
            that.$utils.validateImg(file).then((status) => {
                if (status) {
                    let uploadToken = that.$localConfig.upload.uploadToken;
                    that.$axios.$get(uploadToken).then((res) => {
                        let key = Date.now() + "_" + file.name;
                        let token = res.data.uploadToken;
                        let domain = res.data.domain;
                        let config = { useCdnDomain: true, region: null };
                        let putExtra = {
                            fname: "",
                            params: {},
                            mimeType: [],
                        };

                        let observable = qiniu.upload(
                            file,
                            key,
                            token,
                            putExtra,
                            config
                        );

                        observable.subscribe({
                            next() {},
                            error() {},
                            complete(data) {
                                let image_url =
                                    "http://" + domain + "/" + data.key;

                                const fileObj = {
                                    name: image_url,
                                    url: that.$utils.splicingImageUrl(
                                        image_url
                                    ),
                                };

                                this.multiple
                                    ? that.fileList.push(fileObj)
                                    : (that.fileList = [fileObj]);

                                that.emitSuccess(); // 调用回调
                            },
                        });
                    });
                }
            });
        },

        /**
         * 删除对应的file
         */
        removeUpload(index) {
            this.fileList.splice(index, 1);

            this.emitRemove(); // 调用回调函数
        },

        /**
         * 上传回调处理
         */
        emitSuccess() {
            const fileStr = this.fileList.map((item) => item.name).join(",");
            this.onSuccess(fileStr, this.fileList);
        },

        /**
         * 删除回调处理
         */
        emitRemove() {
            const fileStr = this.fileList.map((item) => item.name).join(",");
            this.onRemove(fileStr, this.fileList);
        },
    },
    watch: {
        value(newV) {
            newV ? this.init(newV) : this.reset();
        },
    },
};
</script>

<style lang="less" scoped>
/deep/.el-upload__input {
    display: none !important;
}
</style>
